package com.xueyu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xueyu.dao.CommunityDao;
import com.xueyu.dao.TermDao;
import com.xueyu.domain.TermBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/term")
public class TermController{
    @Autowired
    TermDao termDao;
    @Autowired
    CommunityDao communityDao;
    Map<String,Object> map = new HashMap<>();

    @RequestMapping("/list")
    public Map<String,Object> init(HttpServletRequest req){
        int pageSize = Integer.parseInt(req.getParameter("pageSize"));
        int curPage = Integer.parseInt(req.getParameter("curPage"));
        String search = req.getParameter("search");
        QueryWrapper<TermBean> queryWrapper = new QueryWrapper<TermBean>();
        Page<TermBean> page = new Page<TermBean>(curPage,pageSize);
        queryWrapper.like("termName",search)
                .or().like("termRemark",search)
                .or().like("c.communityName",search);
        List<TermBean> list = termDao.selectLeftJoin(page,queryWrapper);
        map.put("list",list);
        map.put("code",200);
        map.put("total",page.getTotal());
        return map;
    }

    @RequestMapping("/insert")
    public Map insert(@RequestBody List<TermBean> list) {
        try {
            System.out.println("楼栋信息" + list);
            for (TermBean term : list) {
                termDao.insert(term);
            }
            // 假设处理成功，返回成功的信息
            map.put("success", true);
            map.put("message", "楼栋数据处理成功");
        } catch (Exception e) {
            // 处理异常情况
            e.printStackTrace();
            map.put("success", false);
            map.put("message", "楼栋数据处理失败：" + e.getMessage());
        }
        return map;
    }


    @RequestMapping("/update")
    public Map update(TermBean termBean){
        map.put("changed",(termDao.updateById(termBean) > 0));
        return map;
    }
    @RequestMapping("/del/{id}")
    public Map del(@PathVariable("id") int id){
        map.put("delChanged",(termDao.deleteById(id) > 0));
        return map;
    }

    private boolean repeat(TermBean termBean){
        Map<String,Object> map1 = new HashMap<>();
        QueryWrapper<TermBean> queryWrapper = new QueryWrapper<>();
        map1.put("communityId",termBean.getCommunityId());
        map1.put("termName",termBean.getTermName());
        queryWrapper.allEq(map1);
        return termDao.selectOne(queryWrapper) != null;
    }
}
